/*
 * @Author: 张笑天
 * @Date: 2018-03-07 17:10:25
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-08-28 17:40:14
 */
import React from 'react';
import { routerShape } from 'react-router';
import { asyncComponent } from 'react-async-component';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import {
  Button,
  Modal,
  Icon,
  Dropdown,
  Menu,
  Progress,
  Popover,
  Spin,
  Tooltip,
  Radio,
  Alert,
  message,
} from 'antd';
import {
  WeaErrorPage,
  WeaTools,
  WeaNewScroll,
  WeaInput,
  WeaUpload,
  WeaRichText,
  WeaTagGroup,
  WeaCheckbox,
  WeaDatePicker,
  WeaAlertPage,
  WeaError,
  WeaBrowser,
  WeaLocaleProvider,
} from 'ecCom';

import Switch from '../new/Switch';
import Layout from '../new/Layout';
import ContactsTree from '../new/ContactsTree';
import InternalContactsTree from './InternalContactsTree';
import PopoverGroup from '../new/PopoverGroup';
import CreateGroup from '../new/CreateGroup';
import {
  getFileTypeCls,
  noRepeat,
  transfStr,
  emailValidate,
} from '../../util/index';
import SignEdit from '../emailSetting/sign/Edit';
import TemplateEdit from '../emailSetting/template/Edit';
import AccountNew from '../emailSetting/account/New';

const getLabel = WeaLocaleProvider.getLabel;
const MAILPAGENAME = 'EMIALNEW';
const { confirm } = Modal;
const { Item: MenuItem } = Menu;
const { tryCatch, viewer } = WeaTools;
const RadioGroup = Radio.Group;

const toJSON = data =>
  JSON.stringify(
    toJS(data).map(({ id, type, userids }) => {
      userids = userids == undefined ? id : userids;
      return { id, type, userids };
    }),
  );

const stores = [
  'emailMainStore',
  'emailNewStore',
  'emailCreateGroupStore',
  'emailOpsStore',
  'settingStore',
  'routing',
];

@tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@sg914o`}
      msg={
        props.error ||
        getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)
@inject(...stores)
@observer
class New extends React.Component {
  static displayName = 'New';
  static contextTypes = {
    router: routerShape,
  };
  constructor(props) {
    super(props);
    this.prefixClass = 'wea-email-new';
    this.state = {
      richStatus: '',
      themeFontSize:
        localStorage.getItem('theme-themeInfo') &&
        JSON.parse(localStorage.getItem('theme-themeInfo')).themeFontSize,
      errorMsgVisible: false,
      isSpaceFull: false,
      templateVisible: false,
      signVisible: false,
      accountNewVisible: false,
      ondragupload: false,
    };
    this.texttypeClickValue = '';
    this.isFw = undefined;
    this.autoSaveDraftTimer = null;
  }
  componentDidMount() {
    const {
      location: { query },
      emailNewStore: {
        getInit,
        getSignList,
        getTemplateList,
        getHrmGroup,
        setState,
      },
      fwquery,
      emailOpsStore: {
        emailSize: { remainspace, userid },
      },
      emailOpsStore,
    } = this.props;
    const querys = { ...query, ...fwquery };
    setState({ clearInstance: this.clearInstance });
    // getInit(querys, () => this.changeInternal(query));
    getInit(querys, (res) => {
      this.autoSaveBegin(res.emailAddBean);
    });
    getSignList(query);
    getTemplateList(query);
    getHrmGroup();
    this.isFw = fwquery;
    if (typeof fwquery === 'undefined') {
      this.setSpaceData(userid, remainspace);
    } else {
      // 流程催办弹框才走这个--空间数据请求
      emailOpsStore.getEmailSize().then((res) => {
        this.setSpaceData(res.userid, res.remainspace);
      });
    }

    // if use router to change module, need this code
    // const { route, emailMainStore } = this.props;
    // const { router } = this.context;
    // router.setRouteLeaveHook(route, ({ pathname }) => {
    //   // Warnning when go forward router out of main
    //   const { tabInfo, canGoOut } = emailMainStore;
    //   if (pathname.indexOf('main/email') < 0 && !canGoOut
    //     && checkKeyinTab(tabInfo, 'new')) {
    //     confirm({
    //       content: '您有正在编写的邮件，确定离开？',
    //       onOk: () => {
    //         // Save to draft
    //         emailMainStore.setState({ canGoOut: true });
    //         router.push(pathname);
    //       },
    //     });
    //     return false;
    //   }
    // });
    // this.dragUpload();
  }

  componentWillReceiveProps(nextProps) {
    // 两种方式可参考
    /*
    if (this.props.random != nextProps.random) {
      const { location: { query }, emailNewStore: {
        getInit, getSignList, getTemplateList, getHrmGroup,
      } } = this.props;
      getInit(query);
      getSignList(query);
      getTemplateList(query);
      getHrmGroup();
    } */
    // 内部控制执行

    const {
      location: { query },
      emailNewStore,
      emailNewStore: {
        getInit,
        getSignList,
        getTemplateList,
        getHrmGroup,
        clear,
        sendingStatus,
        changeToNewPage,
        setState,
        autoSave,
      },
      fwquery,
      emailMainStore,
    } = this.props;
    const querys = { ...query, ...fwquery };

    this.isFw = fwquery;
    if (
      !(typeof this.props.visible === 'undefined') &&
      this.props.visible === false &&
      !(typeof nextProps.visible === 'undefined') &&
      nextProps.visible === true
    ) {
      if (typeof fwquery === 'undefined') {
      } else {
        // 流程催办弹框才走这个（发信成功后清理）
        clear();
      }
      this.clearAutoSaveInterval();
      getInit(querys);
      getSignList(query);
      getTemplateList(query);
      getHrmGroup();
    }
    if (autoSave) {
      if (
        this.props.location.pathname.endsWith('/new') &&
        !nextProps.location.pathname.endsWith('/new')
      ) {
        // 出写信页面
        // 在写信页面的时候，退出自动保存一次草稿
        const status = ['success', 'sending', 'error'];
        if (!status.includes(sendingStatus)) {
          setTimeout(() => {
            this.onDraft(() => {
              // 为了处理自动保存草稿后到草稿箱没有自动刷新列表的问题
              if (
                nextProps.location.pathname.endsWith('email/draft') &&
                emailMainStore.listSearch
              ) {
                emailMainStore.listSearch();
              }
              emailNewStore.setState({ editing: true, sendingStatus: '' });
            });
            this.clearAutoSaveInterval();
            setState({ changeToNewPage: false });
          }, 0);
        }
      } else if (changeToNewPage) {
        // 从其他页面切换TAB页切回来的，需要重新启动自动保存草稿
        this.clearAutoSaveInterval();
        this.autoSaveBegin();
      }
    }
  }

  componentWillUnmount() {
    this.richText = null;
    this.richInstanceReady = false;
    this.clearAutoSaveInterval();
  }

  clearAutoSaveInterval = () => {
    if (this.autoSaveDraftTimer) {
      clearInterval(this.autoSaveDraftTimer);
    }
    this.autoSaveDraftTimer = null;
  };

  setSpaceData = (userid, remainspace) => {
    if (userid != '1' && parseFloat(remainspace) <= parseFloat(0)) {
      // 管理员不做空间限制
      this.setState({ isSpaceFull: true });
    }
  };

  getInstance = (ref) => {
    if (!this.richText) {
      this.richText = ref;
    }
  };

  clearInstance = () => {
    if (this.richText || this.richInstanceReady) {
      this.richText = null;
      this.richInstanceReady = false;
    }
  };

  handleStatusChange = (status) => {
    this.setState({ richStatus: status });
    if (status === 'ready') {
      this.richInstanceReady = true;
      this.richText.focus('first');
      $(
        this.richText.editor &&
          this.richText.editor.document &&
          this.richText.editor.document.$.body,
      ).on('click', () => {
        this.hide();
      });
    }
  };

  // 开始自动保存草稿
  autoSaveBegin = (res) => {
    const {
      emailNewStore: { autoSave, autofrequency },
    } = this.props;
    let need_autoSave = (res && res.autoSave) || autoSave,
      need_autofrequency =
        (res && res.saveInterval * 60 * 1000) || autofrequency;
    if (String(need_autoSave) === '1' && need_autofrequency >= 3 * 60 * 1000) {
      // need_autofrequency = 3000;
      this.autoSaveDraft(need_autofrequency);
    }
  };

  // 自动保存草稿
  autoSaveDraft = (autofrequency) => {
    const aotuSavaFun = () => {
      if (this.richInstanceReady) {
        this.onDraft(() => {
          this.props.emailNewStore.setState({
            editing: true,
            sendingStatus: '',
          });
        });
      }
    };
    this.autoSaveDraftTimer = setInterval(aotuSavaFun, autofrequency);
  };

  // 附件上传支持拖拽上传
  dragUpload = () => {
    const compMain = document.getElementsByClassName(
      `${this.prefixClass}-main`,
    )[0];
    let lastEnter = null;

    // document.addEventListener("dragover", function( event ) {
    //   // 阻止默认动作
    //   event.preventDefault();
    // }, false);

    // document.addEventListener("drop", function( event ) {
    //   // 阻止默认动作（如打开一些元素的链接）
    //   event.preventDefault();
    //   // 移动拖动的元素到所选择的放置目标节点
    //   const files = Array.from(event.dataTransfer.files);
    //   console.log('_this.refs.upload', _this.refs.upload)
    //   if (_this.refs.upload) {
    //     _this.refs.upload.uploader.addFile(files);
    //     _this.refs.upload.uploader.start();
    //   }
    // }, false);

    if (compMain) {
      compMain.addEventListener(
        'dragover',
        (e) => {
          e.preventDefault();
          e.stopPropagation();
        },
        false,
      );
      compMain.addEventListener(
        'dragenter',
        (e) => {
          e.preventDefault();
          e.stopPropagation();
          lastEnter = e.target; // 最后进入的元素
          this.setState({ ondragupload: true });
        },
        false,
      );
      compMain.addEventListener(
        'dragleave',
        (e) => {
          e.preventDefault();
          e.stopPropagation();
          if (lastEnter === e.target) {
            this.setState({ ondragupload: false });
          }
        },
        false,
      );
      compMain.addEventListener(
        'drop',
        (e) => {
          e.preventDefault();
          e.stopPropagation();
          const files = Array.from(e.dataTransfer.files);
          // console.log('this.refs.upload', this.refs.upload, e.target.className, e.target.className.endsWith('forbidden-child'))
          if (this.refs.upload) {
            this.refs.upload.uploader.addFile(files);
            this.refs.upload.uploader.start();
            this.setState({ ondragupload: false });
          }
        },
        false,
      );
    }
  };

  hide() {
    [0, 1].forEach((n) => {
      this.refs[`popover_${n}`] &&
        this.refs[`popover_${n}`].refs.tooltip.setState({ visible: false });
    });
    ['To', 'Cc', 'Bcc'].forEach((n) => {
      this.refs[`send${n}_internal`] && this.refs[`send${n}_internal`].hide();
    });
  }

  getTime = (now, time) => {
    let a = now.replace(/-/g, '').replace(' ', '').replace(':', '');
    let b = time.replace(/-/g, '').replace(' ', '').replace(':', '');
    return a * 1 - b * 1;
  };
  onSubmit = (p = {}, callback) => {
    let canSubmit = true;
    let {
      emailNewStore: {
        initDatas: {
          fileInfos: { fileList: fl },
        },
        doSubmit,
        mailid,
        oldmailid,
        mailAccountId,
        hrmAccountid,
        isInternal,
        isSendApart,
        flag,
        sendTo_internal,
        internaltonewIds,
        sendTo_outer,
        sendCc_internal,
        internalccnewIds,
        sendCc_outer,
        sendBcc_internal,
        internalbccnewIds,
        sendBcc_outer,
        subject,
        content,
        fileList,
        priority,
        savesend,
        texttype,
        needReceipt,
        op_isTimingSend,
        timingdate,
        sendFrom_outer,
        email_sendsessionUUid,
        classification,
        resourceClassification,
        penClassification,
      },
      emailOpsStore: {
        emailSize: { remainspace, userid },
      },
    } = this.props;
    let nowTime = this.formatDate(new Date(), 'yyyy-MM-dd HH:mm');
    let timeDate = this.getTime(nowTime, timingdate);
    if (userid != '1' && parseFloat(remainspace) <= parseFloat(0)) {
      // 管理员不做空间限制
      canSubmit = false;
      confirm({
        content: getLabel(
          '83075',
          '个人可用空间已满，请删除部分邮件后再进行发送',
        ),
      });
    }

    if (
      texttype !== 1 &&
      this.richInstanceReady &&
      this.richText &&
      !this.richText.checkMode()
    ) {
      message.error(
        getLabel(
          '384536',
          '不能以源码模式或markdown模式保存，请将编辑器切换到可视化模式',
        ),
      );
      canSubmit = false;
    }

    const sendTo = isInternal ? sendTo_internal : sendTo_outer;
    if (
      (sendTo.length === 0 ||
        (toJS(sendFrom_outer)[0] &&
          toJS(sendFrom_outer)[0].key === '' &&
          isInternal === 0) ||
        !subject) &&
      !p.savedraft
    ) {
      canSubmit = false;
      confirm({
        content: `${
          toJS(sendFrom_outer)[0] &&
          toJS(sendFrom_outer)[0].key === '' &&
          isInternal === 0
            ? getLabel('506447', '发件人不能为空！请先配置外部邮箱')
            : sendTo.length === 0
            ? getLabel(2046, '收件人') + getLabel(82241, '不能为空！')
            : getLabel(344, '主题') + getLabel(82241, '不能为空！')
        }`,
      });
    }
    let regMail = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
    let validate =
      toJS(sendTo_outer) &&
      toJS(sendTo_outer).some(item => !regMail.test(item.id));
    let _validate =
      toJS(sendCc_outer) &&
      toJS(sendCc_outer).some(item => !regMail.test(item.id));
    let __validate =
      toJS(sendBcc_outer) &&
      toJS(sendBcc_outer).some(item => !regMail.test(item.id));
    if (!isInternal && (validate || _validate || __validate)) {
      canSubmit = false;
      confirm({ content: getLabel('18779', '邮件地址格式错误') });
    }

    if (op_isTimingSend === 1 && timingdate === '' && canSubmit) {
      canSubmit = false;
      confirm({ content: getLabel('506448', '定时发送时间不能为空') });
    }
    if (
      op_isTimingSend === 1 &&
      timeDate > 0 &&
      p.savedraft !== 1 &&
      canSubmit
    ) {
      canSubmit = false;
      confirm({ content: getLabel(32030, '发送时间不能晚于当前时间') });
    }

    if (subject && subject.length > 300) {
      canSubmit = false;
      confirm({ content: getLabel('520157', '请填写正确的邮件主题') });
    }

    if (
      penClassification &&
      JSON.stringify(toJS(resourceClassification)) !== '{}' &&
      isInternal &&
      !classification[hrmAccountid]
    ) {
      canSubmit = false;
      this.refs['email-secrecy'].showError();
    }

    const limited = this.getSendLimit();
    if (limited) {
      message.error(getLabel('523366', '已超出允许的收件人数'));
      canSubmit = false;
    }

    if (!op_isTimingSend && timingdate !== '') {
      timingdate = '';
    }
    const emailContent =
      texttype === 1
        ? content
        : this.richInstanceReady && this.richText && this.richText.getData(); // 获取邮件内容
    if (canSubmit) {
      const hasfile = fileList.length === 0 ? 0 : 1;
      const fileid = fl ? fl.map(f => f.fileid) : [];
      const accids = fileList.map(f => f.fileid);
      const delaccids = fileid.filter(f => accids.indexOf(f) < 0);
      const params = {
        mailid,
        mailAccountId,
        hrmAccountid,
        isInternal,
        isSendApart,
        flag,
        internaltonew: toJSON(sendTo_internal),
        internalccnew: toJSON(sendCc_internal),
        internalbccnew: toJSON(sendBcc_internal),
        internaltonewIds,
        internalccnewIds,
        internalbccnewIds,
        to: `${sendTo_outer.map(s => s.id)}`,
        cc: `${sendCc_outer.map(s => s.id)}`,
        bcc: `${sendBcc_outer.map(s => s.id)}`,
        usernameTo: isInternal
          ? JSON.stringify([])
          : JSON.stringify(
              sendTo_outer.map(v => this.getNameAndAddress(v.name)),
            ),
        usernameCc: isInternal
          ? JSON.stringify([])
          : JSON.stringify(
              sendCc_outer.map(v => this.getNameAndAddress(v.name)),
            ),
        usernameBcc: isInternal
          ? JSON.stringify([])
          : JSON.stringify(
              sendBcc_outer.map(v => this.getNameAndAddress(v.name)),
            ),
        subject,
        mouldtext: emailContent,
        hasfile,
        oldmailid,
        // fileid: `${fileid}`,
        accids: `${accids}`,
        delaccids: `${delaccids}`,
        priority,
        savesend,
        texttype,
        needReceipt,
        op_isTimingSend,
        timingdate,
        ...p,
        sessionUUid: email_sendsessionUUid,
        classification: isInternal ? classification[hrmAccountid] : '',
      };
      doSubmit(params).then((res) => {
        if (res.savedraft === '1') {
          if (callback && typeof callback === 'function') callback();
        }
      });
      if (params.savedraft != 1) {
        this.richText = null;
        this.richInstanceReady = false;
      }
    }
  };
  getNameAndAddress = (value) => {
    let address = value.match(/<(.*?)>/g);
    address =
      address && address.length > 0
        ? address[address.length - 1].replace(/[<>\s]/g, '').trim()
        : value;
    let username = value.match(/^.*</);
    username = username ? username[0].replace(/<$/, '').trim() : '';
    return {
      mailusername: username,
      mailaddress: address,
    };
  };
  onDraft = callback => this.onSubmit({ savedraft: 1 }, callback);
  onContactCollapse = () => {
    const {
      emailNewStore: { setState, hideRight, isInternal },
    } = this.props;
    let newHide = { [Number(isInternal)]: !hideRight[Number(isInternal)] };
    setState({ hideRight: { ...hideRight, ...newHide } });
  };
  onPopoverListClick({ content, subject }, isSign) {
    if (isSign) {
      let signContent = /^<table/.test(content)
        ? content.replace(/<\/table>/, '</table>&nbsp;')
        : content;
      if (this.richInstanceReady) {
        this.richText && this.richText.insertHTML(signContent);
      }
    } else {
      confirm({
        content: getLabel(384366, '使用模板会覆盖当前内容，确定覆盖？'),
        okText: getLabel(826, '确定'),
        onOk: () => {
          if (this.richInstanceReady) {
            // setdata will clear body in iframe. need bind click event again
            this.richText &&
              this.richText.insertHTML(content, 'selection', true, () => {
                $(this.richText.editor.document.$.body).on('click', () => {
                  this.hide();
                });
              });
            this.props.emailNewStore.setState({ subject });
          }
        },
      });
    }
    this.hide();
  }
  onPopoverBtnClick(isSign) {
    isSign
      ? this.refs.newSign.wrappedInstance.newSign('', () =>
          this.setState({ signVisible: true }),
        )
      : this.refs.newTemplate.wrappedInstance.newTemplate('', () =>
          this.setState({ templateVisible: true }),
        );
    this.hide();
  }
  getUpload() {
    const {
      emailNewStore: {
        upSetSub,
        subject,
        fileList,
        fileTotalSize,
        fileTotalNumber,
        setState,
        uploadTypeWhiteAuth,
        fileUploadConfig: {
          attachmentCount,
          perAttachmentSize,
          totalAttachmentSize,
          openUploadType,
          uploadTypeRestriction,
        },
      },
    } = this.props;
    if (!attachmentCount) return <div style={{ height: 10 }} />;
    const max = fileList.length >= attachmentCount;
    const showTip = (
      <div className={`${this.prefixClass}-menu`}>
        <p>
          {getLabel(384369, '附件数量限制')}
          {attachmentCount}
          {getLabel(27591, '个')}
        </p>
        {totalAttachmentSize * 1 !== 0 ? (
          <span>
            {getLabel(84818, '附件总大小限制')}
            {totalAttachmentSize}M
          </span>
        ) : (
          <span>{getLabel('510765', '附件总大小不限制')}</span>
        )}
        {(openUploadType === 1 || openUploadType === '1') &&
          uploadTypeWhiteAuth != '1' && (
            <p style={{ wordBreak: 'break-all' }}>
              {getLabel('515239', '禁止上传类型:{type}').replace(
                '{type}',
                uploadTypeRestriction,
              )}
            </p>
          )}
      </div>
    );
    return (
      <div className={`${this.prefixClass}-main-left-upload`}>
        {[
          <span
            className={`${this.prefixClass}-main-left-upload-btn`}
            style={{ display: max ? 'inline' : 'none' }}
            onClick={() =>
              confirm({
                content: ` ${getLabel(
                  384367,
                  '最多可上传',
                )}  ${attachmentCount}  ${getLabel(
                  83077,
                  '个附件',
                )}，${getLabel(384368, '如需更换，请先删除后再上传!')}`,
              })
            }
          >
            <i className="icon-email-Enclosure" />
            {getLabel(19812, '添加附件')}
          </span>,
          <WeaUpload
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaUpload@e6jjdv@${MAILPAGENAME}addfile`}
            datas={toJS(fileList)}
            ref="upload"
            style={{
              display: 'inline-block',
              padding: 0,
              ...(max ? { width: 0, height: 0, overflow: 'hidden' } : {}),
            }}
            uploadUrl="/api/email/add/uploadFile"
            category="string"
            maxFilesNumber={attachmentCount}
            maxUploadSize={perAttachmentSize}
            totolMaxUploadSize={totalAttachmentSize}
            uploadParams={{}}
            clearWhenReset={false}
            onChange={(ids, list, allList) =>
              setState({
                fileList: allList,
                upSetSub: true,
                ...(!upSetSub && !subject
                  ? { subject: allList[0] && allList[0].filename }
                  : {}),
              })
            }
            onUploading={upStatus => setState({ upStatus })}
            getShowListDatas={(t, b) => {
              setState({ fileListB: b });
            }}
            prohibitType={
              (openUploadType === 1 || openUploadType === '1') &&
              uploadTypeWhiteAuth != '1'
                ? uploadTypeRestriction
                : ''
            }
          >
            <span className={`${this.prefixClass}-main-left-upload-btn`}>
              <i className="icon-email-Enclosure" />
              {getLabel(19812, '添加附件')}
            </span>
          </WeaUpload>,
        ]}
        <Tooltip
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Tooltip@y2zl5b`}
          placement="top"
          title={showTip}
        >
          <span style={{ color: '#ff5114', marginLeft: 10, cursor: 'pointer' }}>
            {perAttachmentSize * 1 === 0
              ? getLabel('510766', '单个附件大小不限制')
              : `${getLabel(
                  24494,
                  '附件大小限制',
                )}${perAttachmentSize}M/${getLabel(27591, '个')}...`}
          </span>
        </Tooltip>
        {fileTotalNumber > 0
          ? `${getLabel(384370, '已成功上传')} ${fileTotalNumber} ${getLabel(
              83077,
              '个附件',
            )}，${getLabel(18609, '共')} ${fileTotalSize}`
          : null}
      </div>
    );
  }
  getUploadList() {
    const {
      emailNewStore: { fileList, fileListB, unPreview },
    } = this.props;
    const { themeFontSize } = this.state;
    return (
      <div className={`${this.prefixClass}-main-left-upload-list`}>
        {fileList.map((file) => {
          const {
            filelink,
            isImg,
            previewUrl,
            filename,
            filesize,
            fileid,
            fileExtendName,
          } = file;
          return (
            <div
              className={`${this.prefixClass}-main-left-upload-list-item`}
              key={fileid}
            >
              <div
                className={`${this.prefixClass}-main-left-upload-list-item-img`}
              >
                {/* eslint-disable */}
                {isImg === "true" ? (
                  [
                    <img
                      data-imgsrc={previewUrl}
                      ref={fileid}
                      src={previewUrl}
                      width={56}
                      height={56}
                      className="formImgPlay"
                      style={{ borderRadius: 4, cursor: "pointer" }}
                      onClick={
                        unPreview == "1"
                          ? () =>
                              message.warning(
                                getLabel(
                                  "520702",
                                  "后台邮件系统设置,禁止附件预览"
                                )
                              )
                          : viewer
                      }
                    />,
                    // <div className={`${this.prefixClass}-main-left-upload-list-item-img-mask formImgPlay`} title={filename} data-imgsrc={previewUrl} src={previewUrl} className="formImgPlay" onClick={viewer}
                    //   // onClick={() => this.refs[fileid].zoom()}
                    // >
                    //   <i className='icon-email-enlarge' />
                    // </div>
                  ]
                ) : (
                  <i
                    className={getFileTypeCls(fileExtendName)}
                    onClick={() => this.previewFile(file)}
                  />
                )}
                {/* eslint-enable */}
              </div>
              <div
                className={`${
                  this.prefixClass
                }-main-left-upload-list-item-content ${
                  (themeFontSize === '14' || themeFontSize === '16') &&
                  'bigSize'
                }`}
              >
                {isImg === 'true' ? (
                  <p title={filename}>{filename}</p>
                ) : (
                  /* eslint-disable */
                  <p title={filename} onClick={() => this.previewFile(file)}>
                    {filename}
                  </p>
                  /* eslint-enable */
                )}
                <p>{filesize}</p>
              </div>
              <div
                className={`${this.prefixClass}-main-left-upload-list-item-ops`}
              >
                <i
                  className="icon-coms-download"
                  title={getLabel(31156, '下载')}
                  onClick={() => window.open(filelink)}
                />
                <i
                  className="icon-email-Save-the-cloud-disk"
                  style={{ display: 'none' }}
                  title={getLabel(384371, '上传到云盘')}
                  onClick={() => {}}
                />
                <Icon
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_Icon@bl8gxq@${MAILPAGENAME}delfile`}
                  type="cross"
                  title={getLabel(91, '删除')}
                  onClick={() => this.refs.upload.doDeleteT(fileid)}
                />
              </div>
            </div>
          );
        })}
        {fileListB.map(
          ({
            name,
            size,
            id,
            progress,
            showProgress,
            error,
            progressStatus,
          }) => (
            <div
              className={`${this.prefixClass}-main-left-upload-list-item ${this.prefixClass}-main-left-upload-list-item-uploading`}
              key={id}
            >
              <div
                className={`${this.prefixClass}-main-left-upload-list-item-img`}
              >
                <i className={getFileTypeCls(/\.[^\.]+$/.exec(name))} />
              </div>
              <div
                className={`${
                  this.prefixClass
                }-main-left-upload-list-item-content ${
                  (themeFontSize === '14' || themeFontSize === '16') &&
                  'bigSize'
                }`}
              >
                <p style={error ? { paddingRight: 70 } : null} title={name}>
                  {name}
                  {error && (
                    <span
                      style={{
                        display: 'inline-block',
                        color: '#f00',
                        position: 'absolute',
                        right: 0,
                      }}
                    >
                      {`（${error}）`}
                    </span>
                  )}
                </p>
                <p>
                  {size / 1024 > 1024
                    ? `${(size / 1024 / 1024).toFixed(2)}MB`
                    : `${(size / 1024).toFixed(2)}KB`}
                </p>
              </div>
              <div
                className={`${this.prefixClass}-main-left-upload-list-item-ops`}
              >
                <Icon
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_Icon@fr64gp@${MAILPAGENAME}delfiles`}
                  type="cross"
                  title={getLabel(91, '删除')}
                  onClick={() => this.refs.upload.doDeleteB(id)}
                />
              </div>
              <div
                className={`${this.prefixClass}-main-left-upload-list-item-progress`}
              >
                {showProgress && (
                  <Progress
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_Progress@6o5uv1@${MAILPAGENAME}progress`}
                    percent={progress}
                    strokeWidth={3}
                    {...(error && progressStatus
                      ? { status: progressStatus }
                      : {})}
                  />
                )}
              </div>
            </div>
          ),
        )}
      </div>
    );
  }

  previewFile = (file) => {
    const {
      emailNewStore: { unPreview },
    } = this.props;
    if (unPreview == '1') {
      // 禁止预览
      message.warning(getLabel('520702', '后台邮件系统设置,禁止附件预览'));
    } else {
      const previewurl = `/spa/email/static/index.html#/main/preview?fileid=${file.id}`;
      openFullWindowHaveBar(previewurl);
    }
  };
  getPopoverListProps({ type }) {
    const {
      emailNewStore: { signList, templateList },
    } = this.props;
    const isSign = type === 'emailSign';
    const list = isSign ? signList : templateList;
    const len = list.length;
    return {
      trigger: 'click',
      placement: 'topLeft',
      ref: `popover_${isSign ? 0 : 1}`,
      overlayClassName: `${this.prefixClass}-main-left-rich-popover`,
      title: (
        <div
          className={`${this.prefixClass}-main-left-rich-popover-list`}
          style={{
            height: (len > 3 ? 4 : len < 1 ? 1 : len) * 30 + 12,
            maxWidth: 300,
          }}
        >
          <WeaNewScroll
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaNewScroll@a9vzle`}
            height="100%"
          >
            {list.length > 0 ? (
              list.map((l, i) => (
                /* eslint-disable */
                <p
                  title={l.title}
                  key={`${l.showname}_${i}`}
                  onClick={() => this.onPopoverListClick(l, isSign)}
                >
                  {l.showname}
                </p>
                /* eslint-enable */
              ))
            ) : (
              <p style={{ textAlign: 'center' }}>
                {getLabel(83553, '暂无数据')}
              </p>
            )}
          </WeaNewScroll>
        </div>
      ),
      content: (
        <div className={`${this.prefixClass}-main-left-rich-popover-btn`}>
          <i
            className="icon-coms-Add-to-o"
            onClick={() => this.onPopoverBtnClick(isSign)}
          />
        </div>
      ),
    };
  }
  getRichText() {
    const {
      emailNewStore: {
        setState,
        content,
        texttype,
        isInternal,
        initDatas: { editerApps_internal = [], editerApps_outer = [] },
      },
      emailMainStore: { userConfig },
    } = this.props;
    const config = isInternal ? editerApps_internal : editerApps_outer;
    const fontSize_defaultSize =
      userConfig &&
      (userConfig.fontsize === '' || userConfig.fontsize == undefined
        ? '12px'
        : `${userConfig.fontsize.replace(
            /px/g,
            '',
          )}/${userConfig.fontsize.replace(/px/g, '')}px`);
    const bottomBarConfig = toJS(config).map((c, index) => {
      const icon = (
        <span className={`${this.prefixClass}-main-left-rich-icon`}>
          <i className={c.show} />
          {c.title}
        </span>
      );
      return {
        ...c,
        show:
          c.name === 'Component' ? (
            <Popover
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Popover@6np8f3@${MAILPAGENAME}${index}`}
              {...this.getPopoverListProps(c)}
            >
              {icon}
            </Popover>
          ) : (
            icon
          ),
      };
    });
    return (
      <div
        className={`${this.prefixClass}-main-left-rich`}
        style={texttype ? { border: 0 } : null}
      >
        {texttype === 1 && (
          <div style={texttype ? null : { height: 0, overflow: 'hidden' }}>
            <WeaInput
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaInput@f56pt0`}
              type="textarea"
              autosize={{ minRows: 6 }}
              value={content}
              onChange={v => setState({ content: v })}
            />
          </div>
        )}
        {texttype === 0 && (
          <div style={texttype ? { height: 0, overflow: 'hidden' } : null}>
            <WeaRichText
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaRichText@hbttbf`}
              ref={this.getInstance}
              value={content}
              ckConfig={{
                toolbar: [
                  [
                    'Source',
                    'Undo',
                    'Redo',
                    '-',
                    'Bold',
                    'Italic',
                    'Underline',
                    'Strike',
                    'Format',
                    'Font',
                    'FontSize',
                    'TextColor',
                    'BGColor',
                    '-',
                    'NumberedList',
                    'BulletedList',
                    '-',
                    'Outdent',
                    'Indent',
                    '-',
                    'JustifyLeft',
                    'JustifyCenter',
                    'JustifyRight',
                    '-',
                    'Image',
                    'Link',
                    'Unlink',
                    '-',
                    'Maximize',
                    'Smiley',
                    'Table',
                  ],
                ],
                uploadUrl: '/api/email/add/uploadImgForRichtext',
                extraPlugins:
                  'image2,widget,widgetselection,clipboard,lineutils',
                removePlugins: 'magicline',
                height: 300,
                fontSize_defaultSize,
              }}
              bottomBarConfig={bottomBarConfig}
              onStatusChange={this.handleStatusChange}
              onToolsChange={transfStr}
            />
          </div>
        )}
      </div>
    );
  }
  getPopoverGroup(ref) {
    const {
      emailCreateGroupStore,
      emailNewStore,
      emailNewStore: {
        setState,
        internaltonewIds,
        internalccnewIds,
        internalbccnewIds,
        hasAll,
        allInfo: al,
        hrmGroup: hg,
      },
    } = this.props;
    return (
      <PopoverGroup
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_PopoverGroup@aixgn5`}
        {...{
          tagKey: ref,
          ref,
          hasAll,
          allInfo: toJS(al),
          hrmGroup: toJS(hg),
          emailCreateGroupStore,
        }}
        onSelect={(key, item) => {
          setState({
            [key]: noRepeat(
              item.type === 'all'
                ? [item]
                : toJS(emailNewStore[key]).concat(
                    item.grouptype === '6'
                      ? item.users
                      : item.grouptype === '4'
                      ? [item]
                      : [],
                  ),
            ),
          });
          if (key === 'sendTo_internal') {
            setState({
              internaltonewIds: `${internaltonewIds},${item.userids}`,
            });
          } else if (key === 'sendCc_internal') {
            setState({
              internalccnewIds: `${internalccnewIds},${item.userids}`,
            });
          } else if (key === 'sendBcc_internal') {
            setState({
              internalbccnewIds: `${internalbccnewIds},${item.userids}`,
            });
          }
        }}
      >
        <i
          title={getLabel(81554, '常用组')}
          className="icon-email-Selection-staff"
        />
      </PopoverGroup>
    );
  }
  setExtraData = (arr, type, data) => {
    for (let item of arr) {
      if (data.indexOf(item.id) === -1 && item.isExtra) {
        let name = item.name.match(/^(.*)</)
          ? item.name.match(/^(.*)</)[1]
          : item.name;
        let userInfo =
          this[`extra_${type}`] &&
          this[`extra_${type}`].filter(
            user => item.id === user.id && name === user.name,
          );
        let userId = userInfo && userInfo[0].userid;
        if (
          this.refs[`outer_${type}`] &&
          this.refs[`outer_${type}`].get() &&
          this.refs[`outer_${type}`].get().datas
        ) {
          let newUsers = this.refs[`outer_${type}`]
            .get()
            .datas.filter(newdata => newdata.id !== userId);
          this.refs[`outer_${type}`].set(newUsers);
        }
      }
    }
  };
  getExtraPopoverGroup(type, dataTag = [], idTag) {
    const {
      emailNewStore: { setState },
    } = this.props;
    return (
      <WeaBrowser
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaBrowser@5bcl9c`}
        customized
        type={17}
        dataParams={{ from: 'email' }}
        memorise
        ref={`outer_${type}`}
        key={`outer_${type}`}
        isSingle={false}
        icon="icon-coms-email"
        iconBgcolor="#a0b0ba"
        title={
          <span>
            {getLabel('518113', '选择外部邮件地址')}
            <span style={{ color: 'red', marginLeft: 3 }}>
              {getLabel('518114', '筛选当前所选人员外部邮箱信息')}
            </span>
          </span>
        }
        onChange={(ids, names, datas) => {
          if (ids && datas && datas.length > 0) {
            let emailArr = datas.map(data => ({
              id: data.email || data.emailspan || '',
              name: data.lastnamespan,
            }));
            this[`extra_${type}`] = emailArr;
            let valueArr = emailArr
              .map(v => `${v.name}< ${v.id} >`)
              .join(',');
            valueArr = {
              name: valueArr,
              id: valueArr,
              validate: true,
              isExtra: true,
            };
            valueArr = [...dataTag, valueArr];
            let valueIds = [...new Set(emailArr.map(v => v.id))];
            let data = [...dataTag.map(v => v.id), ...valueIds];
            this.getSplit(valueArr, data, data, dataTag);
            setState({ [type]: valueArr, [idTag]: data.join() });
            this.refs[`outer_${type}`].set([]);

            // 走接口的处理方式
            // setState({loading: true})
            // filterOutEmail({ ids }).then(res => {
            //   if (res.emailAddress.length === 0) {
            //     message.error(getLabel('518115','当前所选人员暂无邮箱可用'))
            //   } else {
            //     this[`extra_${type}`] = res.emailAddress;
            //     let valueArr = res.emailAddress.map(v => (`${v.name}< ${v.id} >`)).join(',')
            //     valueArr = {name: valueArr, id: valueArr, validate: true, isExtra: true}
            //     valueArr = [...dataTag, valueArr]
            //     let valueIds = [...new Set(res.emailAddress.map(v => v.id))];
            //     let data = [...dataTag.map(v => v.id),...valueIds]
            //     this.getSplit(valueArr, data, data, dataTag)
            //     setState({ [type]: valueArr, [idTag]: data.join() });
            //   }
            //   this.refs[`outer_${type}`].set([])
            //   setState({loading: false})
            // })
          }
        }}
        getRenderModule={(context) => {
          const { isSingle } = context.props;
          const { selectedData } = context.state;
          const disabled = selectedData.length === 0;
          return {
            module_3_1: [
              <Button
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_Button@zlaibs@${MAILPAGENAME}submit`}
                key="submit"
                type="primary"
                disabled={disabled}
                onClick={context.handleOk}
              >
                {[
                  getLabel(385565, '确 定'),
                  isSingle || disabled ? '' : context.count(selectedData),
                ]}
              </Button>,
              <Button
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_Button@c9ywji@${MAILPAGENAME}back`}
                key="back"
                type="ghost"
                onClick={context.handleCancel}
              >
                {getLabel(385567, '取 消')}
              </Button>,
            ],
          };
        }}
      >
        <i
          className="wevicon wevicon-menu-536-53612"
          title={getLabel('520609', '选择内部人员')}
        />
      </WeaBrowser>
    );
  }
  getGroupLabel = text => (
    <div className="label-text">
      <label htmlFor="show-label">{text}</label>
      <span>:</span>
    </div>
  );

  formatDate = (time, str) => {
    let obj = {
      yyyy: time.getFullYear(),
      MM: `0${time.getMonth() + 1}`.slice(-2),
      dd: `0${time.getDate()}`.slice(-2),
      HH: `0${time.getHours()}`.slice(-2),
      mm: `0${time.getMinutes()}`.slice(-2),
    };
    return str.replace(/([a-z]+)/gi, v => obj[v]);
  };
  range = (start, end) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  };
  getMain() {
    let that = this;
    const { richStatus } = this.state;
    let {
      location: { query },
      emailNewStore,
      emailNewStore: {
        setState,
        hideRight,
        isInternal,
        subject,
        loading,
        texttype,
        isSendApart,
        op_isShowSendCc,
        op_isShowSendBcc,
        timingdate,
        op_showMoreOptions,
        option_internal,
        option_outer,
        op_isTimingSend,
        sendTo_internal,
        sendTo_outer,
        sendBcc_internal,
        sendBcc_outer,
        sendCc_internal,
        sendCc_outer,
        getSignList,
        getTemplateList,
        selectedAllTo,
        selectedAllCc,
        selectedAllBcc,
        texttypeClick,
        resourceClassification,
        classification,
        hrmAccountid,
        changeSecrecy,
        flag,
        penClassification,
        autoLoading,
      },
      emailCreateGroupStore,
    } = this.props;

    // 外部邮件数据需要加个unselectable ，防止外部邮件地址能点开人员卡片
    sendTo_outer = toJS(sendTo_outer).map(key => ({
      ...key,
      unselectable: true,
    }));
    sendCc_outer = toJS(sendCc_outer).map(key => ({
      ...key,
      unselectable: true,
    }));
    sendBcc_outer = toJS(sendBcc_outer).map(key => ({
      ...key,
      unselectable: true,
    }));

    const options = isInternal ? toJS(option_internal) : toJS(option_outer);
    const sendTo = isInternal ? toJS(sendTo_internal) : toJS(sendTo_outer);
    const sendCc = isInternal ? toJS(sendCc_internal) : toJS(sendCc_outer);
    const sendBcc = isInternal ? toJS(sendBcc_internal) : toJS(sendBcc_outer);
    const sendApart = noRepeat(sendTo.concat(sendCc).concat(sendBcc));

    const limited = this.getSendLimit();
    let nowTime = this.formatDate(new Date(), 'yyyy-MM-dd HH:mm');
    let dayTime = new Date().getDate();
    let hourTime = new Date().getHours();
    let secondTime = new Date().getMinutes();

    let tag_browserParams = {
      title: isInternal
        ? getLabel('33210', '选择人员')
        : getLabel('522797', '选择邮箱'),
      type: isInternal ? '17' : 'emailOuterInput',
      icon: 'icon-coms-email',
      iconBgcolor: '#a0b0ba',
    };
    return [
      <div className={`${this.prefixClass}-main-left-ops`}>
        {/* eslint-disable */}
        {!isSendApart
          ? [
              <a
                style={{ marginLeft: 8 }}
                onClick={() =>
                  setState({
                    op_isShowSendCc: op_isShowSendCc ^ 1,
                    ...(op_isShowSendCc
                      ? {
                          ...(isInternal
                            ? {
                                sendCc_internal: [],
                                internalccnewIds: "",
                              }
                            : {
                                sendCc_outer: [],
                              }),
                        }
                      : {}),
                  })
                }
              >
                {op_isShowSendCc
                  ? getLabel(201, "取消")
                  : getLabel(611, "添加")}
                {getLabel(2084, "抄送")}
              </a>,
              <a
                onClick={() =>
                  setState({
                    op_isShowSendBcc: op_isShowSendBcc ^ 1,
                    ...(op_isShowSendBcc
                      ? {
                          ...(isInternal
                            ? {
                                sendBcc_internal: [],
                                internalbccnewIds: "",
                              }
                            : {
                                sendBcc_outer: [],
                              }),
                        }
                      : {}),
                  })
                }
              >
                {op_isShowSendBcc
                  ? getLabel(201, "取消")
                  : getLabel(611, "添加")}
                {getLabel(2085, "密送")}
              </a>,
              "|",
            ]
          : null}
        <a
          style={{ marginLeft: 10 }}
          onClick={() => {
            let internaluserids = "";
            sendApart.map((v) => {
              internaluserids = `${internaluserids},${
                v.userids ? v.userids : v.id
              }`;
            });
            setState({
              isSendApart: isSendApart ^ 1,
              op_isShowSendCc: 0,
              op_isShowSendBcc: 0,
              ...(!isSendApart
                ? {
                    ...(isInternal
                      ? {
                          sendTo_internal: sendApart,
                          sendCc_internal: [],
                          sendBcc_internal: [],
                        }
                      : {
                          sendTo_outer: sendApart,
                          sendCc_outer: [],
                          sendBcc_outer: [],
                        }),
                  }
                : {}),
              internaltonewIds: internaluserids,
              internalccnewIds: "",
              internalbccnewIds: "",
            });
          }}
        >
          {isSendApart ? getLabel(201, "取消") : ""}
          {getLabel(127185, "分别发送")}
        </a>
        {/* eslint-enable */}
        <span className={`${this.prefixClass}-main-left-ops-right`}>
          {sendApart.length > 0 ? (
            <span
              onClick={() => {
                emailCreateGroupStore.setState({
                  visible: true,
                  list: sendApart,
                });
              }}
            >
              <i className="icon-email-Create-a-common-group" />
              {isInternal == 1 ? (
                <a>{getLabel(384347, '创建常用组')}</a>
              ) : (
                <a>{getLabel(129761, '创建联系人组')}</a>
              )}
            </span>
          ) : null}
          <a
            style={{ margin: '0 3px 0 16px' }}
            onClick={() => {
              confirm({
                content: getLabel(390594, '确定要清空已选择的收件人吗？'),
                okText: getLabel(826, '确定'),
                onOk: () => {
                  setState(
                    isInternal
                      ? {
                          sendTo_internal: [],
                          sendCc_internal: [],
                          sendBcc_internal: [],
                          internaltonewIds: '',
                          internalccnewIds: '',
                          internalbccnewIds: '',
                        }
                      : {
                          sendTo_outer: [],
                          sendCc_outer: [],
                          sendBcc_outer: [],
                        },
                  );

                  !isInternal &&
                    ['sendTo_outer', 'sendCc_outer', 'sendBcc_outer'].forEach(
                      (v) => {
                        this.refs[`outer_${v}`] &&
                          this.refs[`outer_${v}`].set([]);
                      },
                    );
                },
              });
            }}
          >
            {getLabel(127204, '清空收件人')}
          </a>
          <span
            className={`${this.prefixClass}-main-left-ops-contact`}
            onClick={this.onContactCollapse}
          >
            {hideRight[Number(isInternal)] ? (
              isInternal ? (
                <i
                  className="icon-coms-Headquarters-o"
                  title={getLabel('517338', '打开人员组织树')}
                />
              ) : (
                <i
                  className="icon-email-Custom-contact"
                  title={getLabel(384361, '打开联系人列表')}
                />
              )
            ) : (
              <Icon
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_Icon@gc4sp1@${MAILPAGENAME}onclose`}
                type="cross"
                title={getLabel(384362, '关闭联系人列表')}
              />
            )}
          </span>
        </span>
      </div>,
      <div className={`${this.prefixClass}-main-left-to`}>
        <WeaTagGroup
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTagGroup@1m2hn9@${MAILPAGENAME}tagto`}
          label={this.getGroupLabel(getLabel(2046, '收件人'))}
          ref="to"
          key={isInternal ? 'internal' : 'extra'}
          placeholder=""
          disabled={isInternal == 1 && selectedAllTo}
          type={isInternal ? '1' : 'emailOuterInput'}
          hasBrowser={true}
          isTag={!isInternal}
          datas={sendTo}
          // splitChar={/[^;].+?(?=;)/}
          isShowGroup={true}
          browserParams={tag_browserParams}
          validate={v => (isInternal ? false : emailValidate(v))}
          validateAll={true}
          customIcon={
            isInternal
              ? this.getPopoverGroup('sendTo_internal')
              : this.getExtraPopoverGroup(
                  'sendTo_outer',
                  sendTo,
                  'internaltonewIds',
                )
          }
          onChange={(v, data, ids) => {
            // if (!isInternal && v.length < sendTo.length) { // 删除
            //   this.setExtraData(sendTo, 'sendTo_outer', data)
            // }
            !isInternal
              ? this.getSplit(v, data, ids, sendTo)
              : sendTo.length < data.length && data.pop(); // 外部邮件时字符串分割，内部邮件时防止data数据污染页面
            setState({
              [isInternal ? 'sendTo_internal' : 'sendTo_outer']: isInternal
                ? noRepeat(v)
                : v,
              internaltonewIds: ids,
            });
          }}
          onFocus={() =>
            (!isInternal
              ? setState({ focusTagGroup: 'sendTo_outer' })
              : setState({ focusTagGroup: 'sendTo_internal' }))
          }
          onBlurReturnFirst={!isInternal}
          noDefault={!isInternal}
        />
        {op_isShowSendCc ? (
          <WeaTagGroup
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTagGroup@qu2a2t@${MAILPAGENAME}tagcc`}
            label={this.getGroupLabel(getLabel(17051, '抄送人'))}
            ref="cc"
            disabled={selectedAllCc}
            key={isInternal ? 'cc' : 'extracc'}
            type={isInternal ? '1' : 'emailOuterInput'}
            hasBrowser={true}
            isTag={!isInternal}
            datas={sendCc}
            isShowGroup={true}
            browserParams={tag_browserParams}
            validate={v => (isInternal ? false : emailValidate(v))}
            validateAll={true}
            customIcon={
              isInternal
                ? this.getPopoverGroup('sendCc_internal')
                : this.getExtraPopoverGroup(
                    'sendCc_outer',
                    sendCc,
                    'internalccnewIds',
                  )
            }
            onChange={(v, data, ids) => {
              // if (!isInternal && v.length < sendCc.length) { // 删除
              //   this.setExtraData(sendCc, 'sendCc_outer', data)
              // }
              !isInternal
                ? this.getSplit(v, data, ids, sendCc)
                : sendCc.length < data.length && data.pop(); // 外部邮件时字符串分割，内部邮件时防止data数据污染页面
              setState({
                [isInternal ? 'sendCc_internal' : 'sendCc_outer']: isInternal
                  ? noRepeat(v)
                  : v,
                internalccnewIds: ids,
              });
            }}
            onFocus={() =>
              (!isInternal
                ? setState({ focusTagGroup: 'sendCc_outer' })
                : setState({ focusTagGroup: 'sendCc_internal' }))
            }
            onBlurReturnFirst={!isInternal}
            noDefault={!isInternal}
          />
        ) : null}
        {op_isShowSendBcc ? (
          <WeaTagGroup
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTagGroup@ssakcx@${MAILPAGENAME}tagbcc`}
            label={this.getGroupLabel(getLabel(81316, '密送人'))}
            ref="bcc"
            disabled={selectedAllBcc}
            type={isInternal ? '1' : 'emailOuterInput'}
            key={isInternal ? 'bcc' : 'extrabcc'}
            hasBrowser={true}
            isTag={!isInternal}
            datas={sendBcc}
            isShowGroup={true}
            browserParams={tag_browserParams}
            validate={v => (isInternal ? false : emailValidate(v))}
            validateAll={true}
            customIcon={
              isInternal
                ? this.getPopoverGroup('sendBcc_internal')
                : this.getExtraPopoverGroup(
                    'sendBcc_outer',
                    sendBcc,
                    'internalbccnewIds',
                  )
            }
            onChange={(v, data, ids) => {
              // if (!isInternal && v.length < sendBcc.length) { // 删除
              //   this.setExtraData(sendBcc, 'sendBcc_outer', data)
              // }
              !isInternal
                ? this.getSplit(v, data, ids, sendBcc)
                : sendBcc.length < data.length && data.pop(); // 外部邮件时字符串分割，内部邮件时防止data数据污染页面
              setState({
                [isInternal ? 'sendBcc_internal' : 'sendBcc_outer']: isInternal
                  ? noRepeat(v)
                  : v,
                internalbccnewIds: ids,
              });
            }}
            onFocus={() =>
              (!isInternal
                ? setState({ focusTagGroup: 'sendBcc_outer' })
                : setState({ focusTagGroup: 'sendBcc_internal' }))
            }
            onBlurReturnFirst={!isInternal}
            noDefault={!isInternal}
          />
        ) : null}
      </div>,
      <div className={`${this.prefixClass}-main-left-subject`}>
        <WeaInput
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaInput@ajvuim@${MAILPAGENAME}subject`}
          value={subject}
          length={300}
          onChange={v => setState({ subject: v })}
        />
        <span>{`${getLabel(344, '主题')} :`}</span>
      </div>,
      <div className={`${this.prefixClass}-main-left-secrecy-container`}>
        {penClassification &&
        JSON.stringify(toJS(resourceClassification)) !== '{}' &&
        isInternal ? (
          <WeaError
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaError@lj8bcp@${MAILPAGENAME}secrecy`}
            tipPosition="bottom"
            ref="email-secrecy"
            error={getLabel('515180', '没有选择密级')}
          >
            <div
              className={`${this.prefixClass}-main-left-secrecy wea-tag-group`}
            >
              <span>{getLabel('515181', '密级：')}</span>
              <RadioGroup
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_RadioGroup@cmz426@${MAILPAGENAME}secrecy`}
                disabled={!(flag === -1 || flag === 4)}
                value={classification[hrmAccountid]}
                onChange={(v) => {
                  confirm({
                    content: getLabel(
                      '515182',
                      '变更密级，发送时，不符合密级要求的收件人将被过滤，请注意收件人是否属于合适密级。',
                    ),
                    okText: getLabel(826, '确定'),
                    onOk: () => {
                      /* 密级：机密-1， 秘密-2， 内部-3， 公开-4 */
                      /* 3-4之间切换不走接口 */
                      const newClsFic = v.target.checked ? v.target.value : '';
                      if (
                        !(
                          (newClsFic === '3' &&
                            classification[hrmAccountid] === '4') ||
                          (newClsFic === '4' &&
                            classification[hrmAccountid] === '3')
                        )
                      ) {
                        let params = {
                          internaltonew: toJSON(sendTo_internal),
                          internalccnew: toJSON(sendCc_internal),
                          internalbccnew: toJSON(sendBcc_internal),
                          classification: newClsFic,
                          hrmAccountid,
                        };
                        changeSecrecy(params);
                      }
                      setState({
                        classification: {
                          ...toJS(classification),
                          [hrmAccountid]: newClsFic,
                        },
                      });
                    },
                  });
                }}
              >
                {toJS(resourceClassification)[hrmAccountid] &&
                  toJS(resourceClassification)[hrmAccountid].map(option =>
                    (option.visible ? (
                      <Radio
                        ecId={`${
                          (this && this.props && this.props.ecId) || ''
                        }_Radio@4xl5gl@${MAILPAGENAME}${option.key}`}
                        key={option.key}
                        value={option.key}
                      >
                        {option.showname}
                      </Radio>
                    ) : null),
                  )}
              </RadioGroup>
            </div>
          </WeaError>
        ) : null}
      </div>,
      this.getUpload(),
      this.getUploadList(),
      this.getRichText(),
      <div className={`${this.prefixClass}-main-left-footer`}>
        <Button
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Button@zzm7si@${MAILPAGENAME}onsubmit`}
          type="primary"
          onClick={() => this.onSubmit()}
          disabled={
            loading ||
            autoLoading ||
            ((String(texttype) === '0' || String(texttype) === '') &&
              richStatus !== 'ready') ||
            limited
          }
          title={
            limited
              ? getLabel(
                  '511710',
                  '已超出允许的收件人数，请删除部分收件人或分批发送',
                )
              : ''
          }
        >
          {getLabel(2083, '发送')}
        </Button>
        <Button
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Button@9swtz5@${MAILPAGENAME}onsavedraft`}
          style={{ marginLeft: 16 }}
          type="ghost"
          onClick={this.onDraft}
          disabled={
            loading ||
            autoLoading ||
            ((String(texttype) === '0' || String(texttype) === '') &&
              richStatus !== 'ready') ||
            limited
          }
        >
          {getLabel(384355, '存草稿')}
        </Button>
        {options.length > 0 ? (
          /* eslint-disable */
          <span
            className={`${this.prefixClass}-main-left-footer-more`}
            onClick={() =>
              setState({ op_showMoreOptions: op_showMoreOptions ^ 1 })
            }
          >
            {op_showMoreOptions
              ? getLabel(16636, "隐藏")
              : getLabel(17499, "更多")}
            {getLabel(1025, "选项")}
            <i
              className={`icon-coms-right ${
                op_showMoreOptions ? "icon-coms-right-to-left" : ""
              }`}
            />
          </span>
        ) : /* eslint-enable */
        null}
        {op_showMoreOptions
          ? options.map(({ key, label }) => (
              <span
                key={key}
                className={`${this.prefixClass}-main-left-footer-check`}
              >
                <WeaCheckbox
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_WeaCheckbox@s43jic@${MAILPAGENAME}${key}`}
                  value={emailNewStore[key]}
                  onChange={(v) => {
                    if (key == 'texttype') {
                      if (v === '1') {
                        confirm({
                          title: getLabel(
                            '31242',
                            '转换至文本编辑会丢失格式设置,确定切换吗?',
                          ),
                          content: '',
                          okText: getLabel(826, '确定'),
                          onOk() {
                            setState({ [key]: Number(v) });
                            if (texttypeClick === 1) {
                              that.texttypeClickValue = -1;
                            } else if (texttypeClick === -1) {
                              that.texttypeClickValue = 1;
                            }
                            let content =
                              (that.richText && that.richText.getData()) || '';
                            setState({
                              texttypeClick: that.texttypeClickValue,
                              content,
                            });
                            that.richText = null;
                            that.richInstanceReady = false;
                          },
                          onCancel() {
                            setState({ [key]: 0 });
                            if (texttypeClick === 0) {
                              that.texttypeClickValue = -1;
                            } else if (texttypeClick === -1) {
                              that.texttypeClickValue = 0;
                            } else if (texttypeClick === 1) {
                              that.texttypeClickValue = -1;
                            }
                            setState({
                              texttypeClick: that.texttypeClickValue,
                            });
                          },
                        });
                      } else {
                        setState({ [key]: Number(v) });
                      }
                    } else {
                      setState({ [key]: Number(v) });
                    }
                  }}
                />
                <span>{label}</span>
              </span>
            ))
          : null}
        {op_showMoreOptions && op_isTimingSend ? (
          <WeaDatePicker
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaDatePicker@k1o768@${MAILPAGENAME}timingdate`}
            showTime
            format="yyyy-MM-dd HH:mm"
            value={timingdate}
            startValue={nowTime}
            onChange={v => setState({ timingdate: v })}
            needSecond
            disabledTimeConfig={{
              dayConfig: {
                [dayTime]: {
                  disabledHour: this.range(0, hourTime),
                  HourConfig: {
                    [hourTime]: {
                      disabledMinute: this.range(0, secondTime),
                      minuteConfig: {
                        [secondTime]: [11],
                      },
                    },
                  },
                },
              },
            }}
          />
        ) : null}
      </div>,
      <SignEdit
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_SignEdit@gydqcd@${MAILPAGENAME}newSign`}
        ref="newSign"
        visible={this.state.signVisible}
        onCancel={() => this.setState({ signVisible: false })}
        onSubmit={() => getSignList(query)}
      />,
      <TemplateEdit
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_TemplateEdit@b71iv3@${MAILPAGENAME}newTemplate`}
        ref="newTemplate"
        visible={this.state.templateVisible}
        onCancel={() => this.setState({ templateVisible: false })}
        onSubmit={() => getTemplateList(query)}
      />,
      <CreateGroup
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_CreateGroup@qtzmt3@${MAILPAGENAME}createGroup`}
        isInternal={isInternal}
      />,
    ];
  }

  getSplit(v, data, ids, oldData) {
    if (oldData.length < v.length) {
      let lastEmail = v.length > 0 && v.pop(); // 获取数组最后一项
      data.pop();
      if (!lastEmail.optId && !lastEmail.idspan) {
        // 判断是否为回车事件添加的添加数据
        let splitChar = ';,'; // 定义分隔符
        let matchRegExp = new RegExp(
          `[^${splitChar}].*?(?=([${splitChar}](?=[^>]*(?:<|$))))|[^${splitChar}].*?.?$`,
          'g',
        ); // 分隔符分割输入的数据
        let changeRegExp = new RegExp('<(.+?)>', 'g'); // 查找是否存在<>
        let replaceRegExp = new RegExp('[<>\\s]+', 'g'); // 去除<>及空格
        // let mailReg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/g;
        let emailMatch = lastEmail
          ? lastEmail.name.trim().match(matchRegExp)
          : []; // 判断最后一项是否存在数据
        // v.pop();
        // data.pop();
        let lastValue = [];
        emailMatch &&
          emailMatch.length > 0 &&
          emailMatch.map((item) => {
            item = item.trim();
            let change = item.match(changeRegExp); // 查找是否存在<>
            let username = '';
            if (change) {
              item = item.replace(/[^>]*$/, ''); // 清除最后一个<>后的内容
              username = item.match(/^.*</)[0].replace(/<$/, '').trim(); // 查找最后一个<前的内容
              change = change[change.length - 1].replace(replaceRegExp, '');
              change &&
                (item =
                  // 在<>内邮箱地址两侧添加空格
                  `${username}< ${change} >`);
            } else {
              let searchSpace = item.search(/\s/); // 检测是否存在空格
              if (searchSpace >= 0) {
                change = item.match(/[^\s]*$/)[0]; // 查找最后一个空格后的内容为邮件地址
                username = item.match(/^.*\s/)[0].trim(); // 查找最后一个空格前的内容为用户昵称
                item = `${username}< ${change} >`;
              }
            }
            change = change || item; // 不存在空格或<>时，直接将整个字符串作为地址
            if (
              !v.some(val => val.id === change) &&
              !lastValue.some(val => val.id == change)
            ) {
              // 重复字段验证
              //   let mailArr = change && change.match(mailReg);
              let tempValue = {
                id: change,
                name: item,
                validate: lastEmail.validate,
              };
              if (lastEmail.isExtra) {
                tempValue = { ...tempValue, isExtra: true };
              }
              lastValue.push(tempValue);
            }
          });
        v.push(...lastValue);
      } else {
        // 使用模糊搜索或穿梭款进行
        if (!v.some(val => val.id === lastEmail.id)) {
          v.push(lastEmail);
        }
        // 新老数据过滤
        if (oldData.length > 0) {
          let vMap = {};
          for (let i = 0; i < v.length; i++) {
            let vId = v[i].id;
            if (!vMap[vId]) vMap[vId] = v[i];
            else {
              v.splice(i, 1);
            }
          }
        }
      }
    }
  }
  getAccount() {
    const {
      emailNewStore: {
        isInternal,
        setState,
        sendFrom_internal,
        sendFrom_outer,
        mailAccountId,
        hrmAccountid,
        classification,
        changeSecrecy,
        sendTo_internal,
        sendCc_internal,
        sendBcc_internal,
      },
      routing,
    } = this.props;
    const sendFrom = isInternal ? sendFrom_internal : sendFrom_outer;
    if (sendFrom.length === 0) return null;
    let show = toJS(sendFrom).filter(
      s => s.key === (isInternal ? hrmAccountid : mailAccountId),
    );
    show = (show && show[0] && show[0].showname) || '';
    const warning = (
      <span
        style={{ color: 'red' }}
        onClick={() => routing.push('main/email/setting/mailAccount')}
      >
        {getLabel('506449', '暂无发件人，请先配置外部邮箱')}
      </span>
    );
    if (isInternal === 0 && toJS(sendFrom_outer)[0].key === '') return warning;
    return sendFrom.length > 1 ? (
      <Dropdown
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Dropdown@npd8fx`}
        overlay={
          <Menu
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Menu@3rpag4`}
            className={`${this.prefixClass}-menu`}
            onClick={({ key }) => {
              setState({
                [isInternal ? 'hrmAccountid' : 'mailAccountId']: key,
              });
              if (isInternal) {
                let params = {
                  internaltonew: toJSON(sendTo_internal),
                  internalccnew: toJSON(sendCc_internal),
                  internalbccnew: toJSON(sendBcc_internal),
                  classification: toJS(classification)[key],
                  hrmAccountid: key,
                };
                changeSecrecy(params);
              }
            }}
          >
            {sendFrom.map(({ key, showname, masterAccount = true }) => (
              <MenuItem
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_MenuItem@10rtaf@${MAILPAGENAME}${key}`}
                key={key}
              >
                {showname}{' '}
                {isInternal === 1 && (
                  <span
                    className={
                      masterAccount
                        ? 'icon-coms02-Main-account-number'
                        : 'icon-coms02-Secondary-account-number'
                    }
                    style={
                      masterAccount
                        ? { color: '#F5A623', fontSize: 15, paddingLeft: '5px' }
                        : { color: 'grey', fontSize: 15, paddingLeft: '5px' }
                    }
                  />
                )}
              </MenuItem>
            ))}
          </Menu>
        }
        trigger={['click']}
      >
        <span>
          {show}
          <i className="icon-coms-down2" />
        </span>
      </Dropdown>
    ) : (
      show
    );
  }
  getSendOps() {
    const { router } = this.context;
    const {
      emailNewStore: { clear, sendingStatus },
      emailMainStore: { delTab },
      fromCb = false,
    } = this.props;
    // 催办的时候，不显示跳转链接
    return fromCb || typeof this.isFw !== 'undefined' ? (
      <div />
    ) : (
      <div className={`${this.prefixClass}-send-ops`}>
        {sendingStatus === 'error' ? (
          <span
            onClick={() => {
              router.push('/main/email/draft?menu_folderid=-2&folderid=-2');
              delTab('new');
              clear();
            }}
          >
            <i className="icon-email-withdraw" />
            {getLabel(501555, '返回草稿箱')}
          </span>
        ) : (
          <span
            onClick={() => {
              router.push(
                '/main/email/inbox?folderid=0&receivemail=true&receivemailid=0',
              );
              delTab('new');
              clear();
            }}
          >
            <i className="icon-email-withdraw" />
            {getLabel(384356, '返回收件箱')}
          </span>
        )}
        <span
          onClick={() => {
            router.push('/main/email/sent?menu_folderid=-1&folderid=-1');
            delTab('new');
            clear();
          }}
        >
          <i className="icon-email-Unread-o" />
          {getLabel(384357, '查看已发送邮件')}
        </span>
        <span
          onClick={() => {
            router.push('/main/email/new');
            clear();
          }}
        >
          <i className="icon-email-Write-letters" />
          {getLabel(81406, '继续写信')}
        </span>
      </div>
    );
  }
  getSuccess = () => (
    <WeaAlertPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaAlertPage@5moet8`}
      top={200}
      icon={
        <span
          className={`${this.prefixClass}-send-title`}
          style={{ color: '#87d068' }}
        >
          <i className="icon-email-complete" />
          {getLabel(124904, '邮件发送成功')}
        </span>
      }
    >
      {this.getSendOps()}
    </WeaAlertPage>
  );
  getTimingSuccess = () => (
    <WeaAlertPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaAlertPage@yv4t3y`}
      top={200}
      icon={
        <span
          className={`${this.prefixClass}-send-title timing`}
          style={{ color: '#87d068' }}
        >
          <i className="icon-email-complete" />
          {getLabel('32402', '您的定时邮件保存成功')}
          <span>
            {getLabel(
              '501551',
              '该邮件暂时保存在“草稿箱”中，它将在您指定的时间发出',
            )}
          </span>
        </span>
      }
    >
      {this.getSendOps()}
    </WeaAlertPage>
  );

  getSending = () => (
    <WeaAlertPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaAlertPage@h4suq8`}
      top={200}
      icon={
        <span className={`${this.prefixClass}-send-title`}>
          <i className="icon-email-Unread-o" style={{ color: '#4cb3ff' }} />
          {getLabel(384358, '正在发送邮件，请稍后...')}
        </span>
      }
    />
  );
  getError = () => {
    const {
      emailNewStore: { sendRes },
    } = this.props;
    let __errorHint = sendRes.errorMess
      ? (sendRes.errorMess.errorName !== '' || sendRes.errorMess.errorName) &&
        sendRes.errorMess.errorHint
      : getLabel(501327, '邮件发送过程中出现异常,具体点击错误详情');
    return (
      <WeaAlertPage
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaAlertPage@j7j8u8`}
        top={200}
        icon={
          <div
            className={`${this.prefixClass}-send-title errorMess`}
            style={{ color: '#ff5500 ' }}
          >
            <i className="icon-email-error" />
            {getLabel(2045, '邮件发送失败')}
            <span className="email-errorMsg">
              <span>{getLabel(83106, '已保存到草稿箱')}</span>
              <span
                className="errorHint"
                title={__errorHint}
                style={{ color: '#ff5500 ' }}
              >
                {__errorHint}
              </span>
              <span
                onClick={() => {
                  const {
                    sendRes: { errorMess },
                  } = this.props.emailNewStore;
                  confirm({
                    content: (
                      <div className={`${this.prefixClass}-send-errorContent`}>
                        <div
                          className={`${this.prefixClass}-send-errorContent-title`}
                        >
                          {getLabel(24647, '错误提示')}
                        </div>
                        <span
                          className="error_content"
                          dangerouslySetInnerHTML={{
                            __html: errorMess
                              ? errorMess.solution
                              : getLabel(384359, '未知错误，请联系管理员！'),
                          }}
                        />
                        {errorMess && [
                          <div
                            className={`${this.prefixClass}-send-errorContent-title`}
                          >
                            {getLabel(82875, '错误日志')}
                          </div>,
                          <span
                            className="error_content"
                            style={{ color: 'red' }}
                            dangerouslySetInnerHTML={{
                              __html: errorMess && errorMess.errorString,
                            }}
                          />,
                        ]}
                      </div>
                    ),
                  });
                }}
                style={{ color: '#ff5500', fontSize: '1.2em', fontWeight: 700 }}
              >
                {getLabel(83107, '查看错误详情')}
              </span>
            </span>
          </div>
        }
      >
        {this.getSendOps()}
      </WeaAlertPage>
    );
  };

  getLength = (arr) => {
    let num = 0;
    arr.forEach((i) => {
      if (i.type == 'all') {
        // 所有人
        let allNum =
          i.count || i.userids.split(',').filter(v => v !== '').length;
        num += allNum;
      } else if (i.type == 'resource') {
        num += 1;
      } else {
        let usersLength = i.users && i.users.length;
        num += usersLength;
      }
    });
    return num;
  };

  getSentToPerson = () => {
    const {
      emailNewStore: {
        isInternal,
        sendTo_internal,
        sendTo_outer,
        sendCc_internal,
        sendCc_outer,
        sendBcc_internal,
        sendBcc_outer,
      },
    } = this.props;
    const sendTo = isInternal ? toJS(sendTo_internal) : toJS(sendTo_outer); // 收件人
    const sendCc = isInternal ? toJS(sendCc_internal) : toJS(sendCc_outer); // 抄送人
    const sendBcc = isInternal ? toJS(sendBcc_internal) : toJS(sendBcc_outer); // 密送人
    let person = 0;
    let sendToPerson = this.getLength(toJS(sendTo));
    let sendCcPerson = this.getLength(toJS(sendCc));
    let sendBccPerson = this.getLength(toJS(sendBcc));
    person = sendToPerson + sendCcPerson + sendBccPerson;
    return String(person);
  };

  getSendLimit = () => {
    const {
      emailNewStore: {
        initDatas: { sendcount },
      },
    } = this.props;
    const hasSelected = this.getSentToPerson();
    if (String(sendcount) && String(sendcount) === '-1') {
      return false;
    }
    const limited = String(sendcount) && hasSelected > sendcount;
    return limited;
  };

  changeInternal = () => {
    const {
      emailNewStore: { isInternal, sendFrom_outer },
    } = this.props;
    if (isInternal === 0 && toJS(sendFrom_outer)[0].key === '') {
      this.refs.newAccount.wrappedInstance.addAccount(() =>
        this.setState({ accountNewVisible: true }),
      );
    }
  };

  newAccountBack = (status) => {
    const {
      location: { query },
      emailNewStore: { changeAccount },
      fwquery,
    } = this.props;
    const querys = { ...query, ...fwquery };
    if (status) {
      changeAccount(querys);
    }
  };

  render() {
    const { richStatus } = this.state;
    const {
      emailNewStore: {
        hideRight,
        isInternal,
        setState,
        texttype,
        errorSenddate,
        errorHint,
        autoLoading,
        op_showInnerAndOuter,
        sendingStatus,
        loading,
        op_isTimingSend,
        initDatas: { sendcount },
      },
    } = this.props;
    if (sendingStatus === 'success' && op_isTimingSend === 1) {
      return this.getTimingSuccess();
    }
    if (sendingStatus === 'success') return this.getSuccess();
    if (sendingStatus === 'sending') return this.getSending();
    if (sendingStatus === 'error') return this.getError();
    const hasSelected = this.getSentToPerson();
    const limited = this.getSendLimit();
    return (
      <div className={this.prefixClass}>
        <Modal
          ecId={`${(this && this.props && this.props.ecId) || ''}_Modal@6wlzdf`}
          title={getLabel('131329', '信息确认')}
          visible={this.state.isSpaceFull}
          closable={() => this.setState({ isSpaceFull: false })}
          onOk={() => this.setState({ isSpaceFull: false })}
          onCancel={() => this.setState({ isSpaceFull: false })}
          width={380}
          wrapClassName={'spacefull'}
        >
          <span className={`${this.prefixClass}-full`}>
            {getLabel('83075', '个人可用空间已满，请删除部分邮件后再进行发送')}
          </span>
        </Modal>
        <Spin
          ecId={`${(this && this.props && this.props.ecId) || ''}_Spin@mrz9ik`}
          spinning={
            loading ||
            ((String(texttype) === '0' || String(texttype) === '') &&
              richStatus !== 'ready')
          }
        >
          {errorSenddate && (
            <div style={{ marginBottom: -10, marginTop: 10 }}>
              {' '}
              <Alert
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_Alert@z8m9v5`}
                showIcon
                message={getLabel(
                  517413,
                  '当前邮件于{errorSenddate} 发送失败。失败原因：{errorHint}',
                )
                  .replace('{errorSenddate}', errorSenddate)
                  .replace('{errorHint}', errorHint)}
                type="warning"
              />
            </div>
          )}
          <div className={`${this.prefixClass}-top`}>
            <Button
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Button@k5pn1c`}
              style={{ marginLeft: 16 }}
              type="primary"
              onClick={() => this.onSubmit()}
              disabled={
                loading ||
                autoLoading ||
                ((String(texttype) === '0' || String(texttype) === '') &&
                  richStatus !== 'ready') ||
                limited
              }
              title={
                limited
                  ? getLabel(
                      '511710',
                      '已超出允许的收件人数，请删除部分收件人或分批发送',
                    )
                  : ''
              }
            >
              {getLabel(2083, '发送')}
            </Button>
            <Button
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Button@mxejbw`}
              style={{ marginLeft: 16 }}
              type="ghost"
              onClick={this.onDraft}
              disabled={
                loading ||
                autoLoading ||
                ((String(texttype) === '0' || String(texttype) === '') &&
                  richStatus !== 'ready') ||
                limited
              }
            >
              {getLabel(384355, '存草稿')}
            </Button>
            {isInternal &&
            String(sendcount) !== 'undefined' &&
            String(sendcount) !== '-1'
              ? [
                  <span className="limited">
                    {getLabel(
                      '511708',
                      '收件人数量限制为{sendcount}个',
                    ).replace('{sendcount}', sendcount)}
                  </span>,
                  <span className="selected">
                    {getLabel('511709', '当前已选择{hasSelected}个').replace(
                      '{hasSelected}',
                      hasSelected,
                    )}
                  </span>,
                ]
              : null}
            {op_showInnerAndOuter ? (
              <Switch
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_Switch@2no2u8`}
                /* eslint-disable */
                checked={isInternal ^ 1}
                /* eslint-enable */
                labels={[
                  getLabel(24714, '内部邮件'),
                  getLabel(31139, '外部邮件'),
                ]}
                onChange={(v) => {
                  /* eslint-disable */
                  setState({
                    isInternal: v ^ 1,
                    focusTagGroup: "",
                    searchValue: "",
                  });
                  /* eslint-enable */
                  // this.changeInternal();
                }}
              />
            ) : null}
            <span className={`${this.prefixClass}-top-account`}>
              {this.getAccount()}
            </span>
          </div>
          <div
            className={`${this.prefixClass}-main ${
              this.state.ondragupload && 'forbidden-child'
            }`}
          >
            <Layout
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Layout@e5kw24`}
              hideRight={hideRight[Number(isInternal)]}
              rightCom={
                isInternal ? (
                  <InternalContactsTree
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_InternalContactsTree@b7yuae`}
                  />
                ) : (
                  <ContactsTree
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_ContactsTree@fg3860`}
                  />
                )
              }
            >
              <WeaNewScroll
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaNewScroll@fujywn`}
                height="100%"
                ref="mainScroll"
                toTop={true}
                onScroll={() => this.hide()}
              >
                <div className={`${this.prefixClass}-main-left`}>
                  <div
                    className={`${this.prefixClass}-main-left-mask`}
                    style={{
                      display: this.state.ondragupload ? 'block' : 'none',
                    }}
                  >
                    请将附件拖拽至此处上传
                  </div>
                  {this.getMain()}
                </div>
              </WeaNewScroll>
            </Layout>
          </div>
          <AccountNew
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_AccountNew@02qj7a`}
            ref="newAccount"
            visible={this.state.accountNewVisible}
            onCancel={() => this.setState({ accountNewVisible: false })}
            onSubmit={this.newAccountBack}
          />
        </Spin>
      </div>
    );
  }
}

export default asyncComponent({
  resolve: () => New,
  LoadingComponent: () => <div>Loading</div>,
});
